package com.ruoyi.flow.listener;

import com.gitee.deeround.jdbchelper.DbAction;
import com.ruoyi.core.entity.BaseMap;
import com.ruoyi.core.util.IdUtil;
import com.ruoyi.flow.domain.Instance;
import com.ruoyi.flow.entity.Constant;
import com.ruoyi.flow.entity.FireContext;

public class InnerTestFlowListener implements FlowListener {

    private DbAction dbAction;

    public InnerTestFlowListener(DbAction dbAction) {
        this.dbAction = dbAction;
    }


    @Override
    public void prepare(FireContext fireContext) {

    }

    @Override
    public void before(FireContext fireContext) {

        String machineId = fireContext.getFlow().getId();

        if (fireContext.getEvent().getId().equals(Constant.Event.START)) {

            BaseMap entity = fireContext.getData();

            entity.put("id", IdUtil.sequenceId());

            String sql = "insert into flow_" + machineId + "(id,name,day,remark) values(?,?,?,?)";
            dbAction.update(sql, new Object[]{
                    entity.getString("id"),
                    entity.getString("name"),
                    entity.getInteger("day"),
                    entity.getString("remark"),
            });
        }

    }

    @Override
    public void after(FireContext fireContext) {

        String machineId = fireContext.getFlow().getId();

        //更新业务数据
        Instance instance = fireContext.getInstance();

        if ("delete".equals(fireContext.getEvent().getId())) {
            dbAction.update("delete from flow_" + machineId + " where id=?", new Object[]{fireContext.getData().getString("id")});
        }

        String sql = "update flow_" + machineId + " set instance_id=?,node_id=?,state=?,name=?,day=?,remark=? where id=?";
        dbAction.update(sql, new Object[]{
                instance.getInstanceId(),
                fireContext.getTarget().getId(),
                fireContext.getTarget().getState(),
                fireContext.getData().getString("name"),
                fireContext.getData().getInteger("day"),
                fireContext.getData().getString("remark"),
                fireContext.getData().getString("id")
        });

    }
}
